package com.yx.shop.service.impl;

import com.yx.shop.common.Const;
import com.yx.shop.dao.AddressDao;
import com.yx.shop.dao.impl.AddressDaoImpl;
import com.yx.shop.entitly.Address;
import com.yx.shop.service.AddressService;
import com.yx.shop.utils.JDBCUtils;

import java.util.List;

/**
 * @Classname AddressServiceImpl
 * @Description TODO:
 * @Date 2021/05/08 20:56
 * @Created by yx
 */
public class AddressServiceImpl implements AddressService {
    private AddressDao addressDao = new AddressDaoImpl();

    @Override
    public List<Address> getAddList(int uid) {
        List<Address> addressList = null;
        try {
            JDBCUtils.begin();
            //state=1为默认地址,降序排序,实现默认地址始终处于第一个数据
            if (uid > 0) {
                addressList = addressDao.getAddList(uid);
            }
            JDBCUtils.commit();
        } catch (Exception e) {
            JDBCUtils.rollback();
            e.printStackTrace();
        }
        return addressList;
    }

    @Override
    public boolean insertAddress(Address address) {
        boolean flag = false;
        try {
            JDBCUtils.begin();
            //设置是否为默认地址.初始不为默认地址
            address.setAstate(Const.AddressInfo.NOT_DEFAULT_ADDREESS);
            if (addressDao.insert(address) > 0) {
                flag = true;
            }
            JDBCUtils.commit();
        } catch (Exception e) {
            JDBCUtils.rollback();
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean deleteAddByAid(Integer aid) {
        boolean flag = false;
        try {
            JDBCUtils.begin();
            if (addressDao.deleteAddByAid(aid) > 0) {
                flag = true;
            }
            JDBCUtils.commit();
        } catch (Exception e) {
            JDBCUtils.rollback();
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean defaultAdd(Integer aid, int uid) {
        boolean flag = false;
        try {
            JDBCUtils.begin();
            //1.先设置该用户所有地址为普通
            int i = addressDao.setNotDefault(uid);
            //2.设置该用户此地址id为默认地址
            int j = addressDao.setDefault(aid);
            if (i > 0 && j > 0) {
                //设置成功
                flag = true;
            }
            JDBCUtils.commit();
        } catch (Exception e) {
            JDBCUtils.rollback();
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean updateAddress(Address address) {
        boolean flag = false;
        try {
            JDBCUtils.begin();
            if (addressDao.updateAdd(address)>0) {
                flag=true;
            }
            JDBCUtils.commit();
        } catch (Exception e) {
            JDBCUtils.rollback();
            e.printStackTrace();
        }
        return flag;
    }
}
